require(['init'], function () {

  var classuid = location.search.urlToObj().classuid

  // var $classname = $('[name=classname]')
  // var $coursename = $('[name=coursename]')
  // var $begindate = $('[name=startdate]')
  // var $lessonsQty = $('[name=class_timelength]')
  // var $quotas = $('[name=max_student]')
  // var $teachername = $('[name=head_teacher]')

  var $submitBtn = $('#J_classinfo_submit');
  if(!classuid) {
    $('#J_lessoninfo').attr('href','javascript:void(0)').css('cursor', 'not-allowed');
  } else {
    $('#J_classinfo')[0].href += '?classuid=' + classuid;
    $('#J_lessoninfo')[0].href += '?classuid=' + classuid;
    $('.breadcrumb .active a').text('编辑班级').attr('href', 'javascript:void(0)')
    $submitBtn.val('保 存');
  }

  function getProducts(query, cb) {
    ajaxMethod({
      url: '/api/products',
      data: query || {},
      success: function (data) {
        cb && cb(data)
      }
    })
  }

  function ClassInfo(options) {
    options = options || {};
    this.data = options.data || this.getDefaultData();
    this.$dom = $('<div class="formList"></div>');

    this.init(this.configList);
  }

  ClassInfo.prototype = {
    constructor: ClassInfo,
    configList: [
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>课程名称',
        content: {
          init: function ($content, root) {
            root.$courseName = $('<input type="text" class="form-control selectInput" data-formcheck="length" style="width: 170px" readonly placeholder="请选择课程名称">').appendTo($content);

            root.$courseName.on('click', function () {
              getProducts({type:1}, function (data) {
                var candidateList = [];
                $.each(data, function (i, item) {
                  candidateList.push({
                    id: item.id,
                    name: item.title,
                    phone: item.price
                  });
                })

                var selector = new ContactSelector({
                  candidateDataList: candidateList,
                  // checkedDataList: teacherViewList.getDataList(),
                  checkedMax: 1,
                  hideAvatar: true,
                  callback: {
                    searchChange: function (searchValue) {
                      if(searchValue === '') {
                        selector.candidateList.update(candidateList)
                      } else {
                        getProducts({
                          type: 1,
                          title: searchValue
                        }, function (data) {
                          var candidateTeacherList = {}
                          $.each(data, function (i, item) {
                            candidateTeacherList[item.teacheruid] = {
                              id: item.id,
                              name: item.title,
                              phone: item.price
                            }
                          })
                          selector.candidateList.update(candidateList)
                        })
                      }
                    },
                    submit: function (checkedDataList) {
                      if( !Object.keys(checkedDataList).length ) {
                        _Tips('请选择课程产品');
                        return false
                      }

                      var productId = selector.getCheckedIdList()[0]
                      root.$courseName.val(checkedDataList[productId].name).change();
                      root.data.courseuid = productId
                    }
                  }
                })
                var tips = '搜索课程名称'
                selector.searchBar.$dom.find('[data-type="search-input"]').attr('data-value',tips).attr('data-tips', tips)
                selector.popUpBox.show();
              })

            })

            root.$courseName.on('change', function () {
              root.data.courseName = $.trim(root.$courseName.val());
            })
          },
          update: function ($content, root, formData) {
            root.$courseName.val(formData.courseName).change();
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>班级名称',
        content: {
          init: function ($content, root) {
            root.$className = $('<input type="text" class="form-control" data-formcheck="length" style="width: 170px">').appendTo($content);
            root.$className.on('change', function () {
              root.data.className = $.trim(root.$className.val());
            })
          },
          update: function ($content, root, formData) {
            root.$className.val(formData.className).change();
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>课程类型',
        content: {
          init: function ($content, root) {
            var courseTypes = root.data.courseTypes;
            var courseTypesArr = [
              {
                dataValue: 0,
                context: '请选择课程类型'
              }
            ]

            $.each(courseTypes, function (i, item) {
              courseTypesArr.push({
                dataValue: item.coursetypeuid,
                context: item.coursetypename
              })
            })

            root.courseTypeInput = new SelectInput({
              inputStyle: { width: 170 },
              optionList: courseTypesArr,
              selected: root.data.courseTypeId,
              onChange: function () {
                root.data.courseTypeId = root.courseTypeInput.value();
                root.data.courseTypeName = root.courseTypeInput.$input.val()

                if(root.data.courseTypeId != 0) {
                  root.courseTypeInput.$dom.attr('data-value', root.data.courseTypeId);
                } else {
                  root.courseTypeInput.$dom.removeAttr('data-value');
                }
              }
            })
            root.courseTypeInput.$dom.attr('data-formcheck', 'length');
            if(root.courseTypeInput.value() != 0) {
              root.courseTypeInput.$dom.attr('data-value', root.courseTypeInput.value());
            }
            root.courseTypeInput.$dom.appendTo($content)

          },
          update: function ($content, root, formData) {
            // root.$courseName.val(formData.courseName).change();
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>课程资源',
        content: {
          init: function ($content, root) {
            root.cloudFileInput=new CloudFileInput({
							selectorMode:'normal',
							callback:{
								done:function(folderData){
									root.data.cloudFolderId=folderData.id;
									root.data.cloudFolderPathStr=folderData.pathStr;
								}
							}
						});
            root.cloudFileInput.$dom.attr('data-formcheck','length');
						root.cloudFileInput.$dom.appendTo($content);
						root.cloudFileInput.$dom.on('click',function(){
							// listForm.popUpBox.$content.scrollTop(100);
						});
          },
          update:function($content,root,formData){
  					root.cloudFileInput.setValue(formData.cloudFolderId, formData.cloudFolderPathStr);
  				}
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>开课日期',
        content: {
          init: function ($content, root) {
            root.startDateInput = new DateInput();
            root.startDateInput.$dom.appendTo($content);
            root.startDateInput.$dom.on('change',function(){
              var startDateTime = new Date(root.startDateInput.value()).getTime();
              root.data.startTime = startDateTime
            });
          },
          update: function ($content, root, formData) {
            var startDayStr = new Date(formData.startTime).Format('YYYY-MM-DD');
            root.startDateInput.minDate(startDayStr);
            root.startDateInput.value(startDayStr);
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>总课时',
        content: {
          init: function ($content, root) {
            root.$courseTimeCount = $('<input type="number" class="form-control" data-formcheck="length" style="width: 170px">').appendTo($content);
            root.$courseTimeCount.on('change', function () {
              root.data.courseTimeCount = $.trim(root.$courseTimeCount.val());
            })
          },
          update: function ($content, root, formData) {
            root.$courseTimeCount.val(formData.courseTimeCount).change();
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>最大人数',
        content: {
          init: function ($content, root) {
            root.$maxCount = $('<input type="number" class="form-control" data-formcheck="length" style="width: 170px">').appendTo($content);
            root.$maxCount.on('change', function () {
              root.data.maxCount = $.trim(root.$maxCount.val());
            })
          },
          update: function ($content, root, formData) {
            root.$maxCount.val(formData.maxCount).change();
          }
        }
      }
    ],

    createFormLi: function (liConfig) {
      var $formLi = $('<div class="formLi"></div>').appendTo(this.$dom);
      $('<div class="formTitle"></div>').html('<span class="titleText">'+ liConfig.title +'</span>').appendTo($formLi);
      var $formContent = $('<div class="formContent"></div>').appendTo($formLi);
      liConfig.content.init($formContent, this);
      if(liConfig.content.update) {
        liConfig.content.update($formContent, this, this.data);
      }
    },

    init: function (liConfigList) {
      $.each(liConfigList, function (i, cur) {
        this.createFormLi(cur)
      }.bind(this));

    },

    getDefaultData: function () {
      return {
        startTime: new Date().getTime()
      }
    }
  }

  //显示班级名称
  function showClassName(classInfo) {
    $('.breadcrumb').append(
      '<li>\
        <a href="javascript:void(0)">'+ classInfo.classname +'</a>\
      </li>'
    );
  }

  /**
   * [getCouseTypes 获取课程类型]
   * @param  {Function} callback [description]
   * @return {[type]}            [description]
   */
  function getCouseTypes(callback) {
    ajaxMethod({
      url: '/api/coursetypes',
      success: function (data) {
        callback(data)
      }
    })
  }

  /**
   * [getClassInfo 获取班级信息]
   * @param  {Function} callback [description]
   * @param  {[type]}   classuid [description]
   * @return {[type]}            [description]
   */
  function getClassInfo(classuid, callback) {
    if(classuid == undefined) {
      return;
    }
    ajaxMethod({
      url: '/api/classe/' + classuid,
      success: function (data) {
        callback(data)
      }
    })
  }

  function bindSubmit(formList) {
    $submitBtn.on('click', function () {
      if(FormCheck.childrenInputCheck(formList.$dom)) {

        var classInfoData = formList.data;
        var postData = {
          classname: classInfoData.className,
          coursename: classInfoData.courseName,
          courseuid: classInfoData.courseuid,
          coursetypeid: classInfoData.courseTypeId,
          coursetypename: classInfoData.courseTypeName,
          folderid: classInfoData.cloudFolderId,
          foldername: classInfoData.cloudFolderPathStr,
          begindate: new Date(classInfoData.startTime).Format('YYYY-MM-DD'),
          lessonsQty: classInfoData.courseTimeCount,
          quotas: classInfoData.maxCount
        }

        if(classuid != undefined) {
          ajaxMethod({
            url: '/api/classe/' + classuid,
            method: 'put',
            data: $.extend(postData, { classuid: classuid }),
            success: function (data, status) {
              _Alert('系统消息', status.message)
            }
          });

        } else {

          ajaxMethod({
            url: '/api/classe',
            method: 'post',
            data: postData,
            success: function (data, status) {
              if(status.code === 0) {
                location.href = 'lessoninfo.html?classuid=' + data.classuid;
              }
            }
          });
        }

      }
    })
  }

  getCouseTypes(function (courseTypes) {
    var classInfoData = {
      courseTypes: courseTypes
    }
    var formList;
    if(classuid != undefined) {
      getClassInfo(classuid, function (data) {
        $.extend(classInfoData, {
          className: data.classname,
          courseName: data.coursename,
          cloudFolderId: data.folderid,
          cloudFolderPathStr: data.foldername,
          startTime: new Date(data.begindate).getTime(),
          courseTimeCount: data.lessonsQty,
          maxCount: data.quotas,
          courseTypeId: data.coursetypeid
        })

        formList = new ClassInfo({
          data: classInfoData
        });

        formList.$dom.appendTo($('#J_classinfo_wrap'))
        bindSubmit(formList);
      })
    } else {
      $.extend(classInfoData, {
        startTime: new Date().getTime(),
      })

      formList = new ClassInfo({
        data: classInfoData
      });

      formList.$dom.appendTo($('#J_classinfo_wrap'))
      bindSubmit(formList);
    }
  })

})
